package com.example.librarymanagementsystembackend.usermanagement.service;

import com.example.librarymanagementsystembackend.utils.InvalidRequestException;
import org.springframework.stereotype.Service;
import com.example.librarymanagementsystembackend.usermanagement.entity.UserAction;
import com.example.librarymanagementsystembackend.usermanagement.mapper.UserActionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserActionService {

    private final UserActionMapper userActionMapper;

    // 构造器
    @Autowired
    public UserActionService(UserActionMapper userActionMapper) {
        this.userActionMapper = userActionMapper;
    }


    // 插入用户操作记录（自动回填ID）
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int createUserAction(UserAction userAction) {
        // 用户操作记录 中的用户ID是否存在?
            // 抛出异常

        return userActionMapper.insert(userAction);
    }


    // 根据主键ID删除操作记录
    public UserAction getUserActionById(Integer id) {
        return userActionMapper.selectById(id);
    }

    // 根据ID删除操作记录
    @Transactional
    public void deleteUserActionById(Integer id) {
        if (userActionMapper.deleteById(id) == 0) {
            throw new InvalidRequestException( "用户" + id + "不存在");
        }
    }

    // 根据用户ID查询操作记录（按时间倒序）
    public List<UserAction> getUserActionsByUserId(Integer userId) {
        return userActionMapper.selectByUserId(userId);
    }

    // 查询指定时间范围内的操作记录
    public List<UserAction> getUserActionsByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return userActionMapper.selectByTimeRange(startTime, endTime);
    }
}